import { requireLogin, showLoginModal } from '../../utils/auth'

const app = getApp()

Page({
  data: {
    shops: [],
    categories: [],
    nearbyShops: [],
    loading: true,
    keyword: '',
    location: null,
    newProducts: [],
    statusBarHeight: 0
  },

  onLoad() {
    // 获取状态栏高度
    const systemInfo = wx.getSystemInfoSync()
    this.setData({
      statusBarHeight: systemInfo.statusBarHeight
    })
    
    this.getLocation()
    this.loadNewProducts()
  },

  onShow() {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0  // 设置对应的索引
      })
    }
  },

  // 获取位置信息
  async getLocation() {
    try {
      const res = await new Promise((resolve, reject) => {
        wx.getLocation({
          type: 'gcj02',
          success: resolve,
          fail: (err) => {
            console.error('获取位置失败:', err) // 调试日志
            reject(err)
          }
        })
      })

      console.log('获取到位置信息:', res) // 调试日志
      
      this.setData({
        location: {
          latitude: res.latitude,
          longitude: res.longitude
        }
      }, () => {
        // 位置信息更新后重新加载店铺
        this.loadShops()
      })
    } catch (error) {
      console.error('获取位置失败：', error)
      // 即使获取位置失败，也加载数据
      this.loadShops()
      
      // 提示用户开启位置权限
      wx.showModal({
        title: '提示',
        content: '需要获取您的位置才能为您推荐附近的店铺，是否开启位置权限？',
        success: (res) => {
          if (res.confirm) {
            wx.openSetting({
              success: (res) => {
                if (res.authSetting['scope.userLocation']) {
                  this.getLocation()
                }
              }
            })
          }
        }
      })
    }
  },

  // 加载数据
  async loadData() {
    try {
      wx.showLoading({ title: '加载中...' })
      await Promise.all([
        this.loadCategories(),
        this.loadShops()
      ])
    } catch (error) {
      console.error('加载数据失败：', error)
    } finally {
      wx.hideLoading()
      this.setData({ loading: false })
    }
  },

  // 加载分类
  async loadCategories() {
    try {
      const db = wx.cloud.database()
      const { data } = await db.collection('shopCategories')
        .orderBy('sort', 'asc')
        .get()
      
      this.setData({ categories: data })
    } catch (error) {
      console.error('加载分类失败：', error)
    }
  },

  // 加载店铺
  async loadShops() {
    try {
      wx.showLoading({ title: '加载中...' })
      const db = wx.cloud.database()
      const _ = db.command

      // 基础查询条件
      const query = {
        status: 'open'
      }

      let shops = []
      if (this.data.location) {
        // 如果有位置信息，计算距离
        const { latitude, longitude } = this.data.location
        console.log('当前位置:', latitude, longitude) // 调试日志
        
        const res = await db.collection('shops')
          .where(query)
          .get()
        
        shops = res.data.map(shop => {
          if (shop.location && shop.location.latitude && shop.location.longitude) {
            const distance = this.calculateDistance(
              latitude,
              longitude,
              shop.location.latitude,
              shop.location.longitude
            )
            console.log(`店铺 ${shop.name} 距离:`, distance) // 调试日志
            return {
              ...shop,
              distance,
              distanceText: this.formatDistance(distance)
            }
          }
          return {
            ...shop,
            distance: Infinity,
            distanceText: '未知'
          }
        })

        // 按距离排序
        shops.sort((a, b) => (a.distance || Infinity) - (b.distance || Infinity))
      } else {
        console.log('未获取到位置信息') // 调试日志
        const res = await db.collection('shops')
          .where(query)
          .get()
        shops = res.data.map(shop => ({
          ...shop,
          distanceText: '未知'
        }))
      }

      console.log('处理后的店铺数据:', shops) // 调试日志

      // 更新数据
      this.setData({
        shops: shops,
        nearbyShops: shops.slice(0, 3)
      })
    } catch (error) {
      console.error('加载店铺失败：', error)
    } finally {
      wx.hideLoading()
    }
  },

  // 计算两点之间的距离（米）
  calculateDistance(lat1, lon1, lat2, lon2) {
    if (!lat1 || !lon1 || !lat2 || !lon2) {
      return null
    }

    const R = 6371000 // 地球半径，单位米
    const dLat = this.toRad(lat2 - lat1)
    const dLon = this.toRad(lon2 - lon1)
    const a = 
      Math.sin(dLat/2) * Math.sin(dLat/2) +
      Math.cos(this.toRad(lat1)) * Math.cos(this.toRad(lat2)) * 
      Math.sin(dLon/2) * Math.sin(dLon/2)
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))
    return R * c
  },

  // 角度转弧度
  toRad(degree) {
    return degree * Math.PI / 180
  },

  // 格式化距离
  formatDistance(meters) {
    if (!meters) return '未知'
    if (meters < 1000) {
      return `${Math.round(meters)}m`
    }
    return `${(meters / 1000).toFixed(1)}km`
  },

  // 搜索
  onSearch(e) {
    const keyword = e.detail.value
    this.setData({ keyword })
    if (keyword) {
      this.searchShops(keyword)
    } else {
      this.loadShops()
    }
  },

  // 搜索店铺
  async searchShops(keyword) {
    try {
      const db = wx.cloud.database()
      const _ = db.command
      const { data } = await db.collection('shops')
        .where({
          status: 'open',
          name: db.RegExp({
            regexp: keyword,
            options: 'i'
          })
        })
        .get()
      
      this.setData({ shops: data })
    } catch (error) {
      console.error('搜索店铺失败：', error)
    }
  },

  // 点击分类
  onCategoryTap(e) {
    const { name } = e.currentTarget.dataset
    this.filterShopsByCategory(name)
  },

  // 按分类筛选店铺
  async filterShopsByCategory(categoryName) {
    try {
      const db = wx.cloud.database()
      const { data } = await db.collection('shops')
        .where({
          status: 'open',
          categories: categoryName
        })
        .get()
      
      this.setData({ shops: data })
    } catch (error) {
      console.error('筛选店铺失败：', error)
    }
  },

  // 进入店铺
  goToShop(e) {
    const { id } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/shops/detail?id=${id}`
    })
  },

  // 加载最新商品
  async loadNewProducts() {
    try {
      const db = wx.cloud.database()
      const { data: products } = await db.collection('products')
        .orderBy('createTime', 'desc')
        .limit(10)
        .get()

      // 加载每个商品的店铺信息
      const productsWithShop = await Promise.all(products.map(async (product) => {
        if (product.shopId) {
          const { data: shop } = await db.collection('shops').doc(product.shopId).get()
          return {
            ...product,
            shopName: shop.name
          }
        }
        return product
      }))

      this.setData({
        newProducts: productsWithShop
      })
    } catch (error) {
      console.error('加载最新商品失败：', error)
    }
  },

  // 跳转到商品详情
  goToProduct(e) {
    const { id } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/products/detail?id=${id}`
    })
  },

  // 收藏商品
  async favoriteProduct(e) {
    if (!checkLogin()) return

    const { id } = e.currentTarget.dataset
    try {
      const db = wx.cloud.database()
      
      // 获取商品信息
      const { data: product } = await db.collection('products').doc(id).get()
      
      // 添加收藏
      await db.collection('favorites').add({
        data: {
          userId: app.globalData.openid,
          product: {
            id: product._id,
            name: product.name,
            price: product.specCombos ? tools.getMinPrice(product.specCombos) : product.price,
            image: product.images[0],
            specCombos: product.specCombos  // 保存规格组合信息
          },
          createTime: db.serverDate()
        }
      })
      
      showToast('已收藏')
    } catch (error) {
      console.error('收藏失败：', error)
      showToast('收藏失败', 'none')
    }
  },

  // 加入购物车

  async addToCart(e) {
    const { id } = e.currentTarget.dataset
    try {
      await wx.cloud.callFunction({
        name: 'addToCart',
        data: { productId: id }
      })
      wx.showToast({
        title: '已加入购物车'
      })
    } catch (error) {
      console.error('加入购物车失败：', error)
      wx.showToast({
        title: '加入失败',
        icon: 'none'
      })
    }
  }
}) 